package com.base.utils;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


public class RsaUtil {
    // 公钥
    private static final String publicKey = "";
    // 秘钥
    private static final String privateKey = "";

    /**
     * 加密字符串
     */
    public static String encrypt(String data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        byte[] infoBytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] encrypt = encrypt(publicKey, infoBytes);
        return Base64.getEncoder().encodeToString(encrypt);
    }

    /**
     * 解密字符串
     */
    public static String decrypt(String data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        byte[] decode = Base64.getDecoder().decode(data);
        byte[] decrypt = decrypt(privateKey, decode);
        return new String(decrypt, StandardCharsets.UTF_8);
    }

    public static byte[] encrypt(String publicKey, byte[] srcBytes) {
        try {
            if (publicKey != null) {
                byte[] decode = Base64.getDecoder().decode(publicKey);
                RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decode));
                Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
                return cipher.doFinal(srcBytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(String privateKey, byte[] srcBytes) {
        try {
            if (privateKey != null) {
                byte[] decode = Base64.getDecoder().decode(privateKey);
                RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decode));
                Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
                cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
                return cipher.doFinal(srcBytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
